package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"goodsroom/cache"
	"goodsroom/models"
	"math"
)

type GoodsroomController struct {
	beego.Controller
}

func (c *GoodsroomController) Add() {
	number := c.GetString("number")
	cate := c.GetString("cate")
	room := c.GetString("room")
	num, _ := c.GetInt("num")
	price, _ := c.GetFloat("price")
	name := c.GetString("name")
	var goodsrooms []*models.Goodsroom
	var goodsroom models.Goodsroom
	goodsroom.Number = number
	goodsroom.Cate = cate
	goodsroom.Room = room
	goodsroom.Num = num
	goodsroom.Price = price
	goodsroom.Name = name

	err := goodsroom.Creates()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "入库失败",
		}
		c.ServeJSON()
		return
	}

	goodsrooms = goodsrooms
	jsonData, _ := json.Marshal(goodsrooms)
	cache.Rdb.Set(cache.Ctx, "goodsroom", &jsonData, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "入库成功",
	}
	c.ServeJSON()
}
func (c *GoodsroomController) List() {
	room := c.GetString("room")
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 5)
	var err error
	var count int64
	models.DB.Model(&models.Goodsroom{}).Count(&count)
	sum := int(math.Ceil(float64(count) / float64(pageSize)))
	up := page - 1
	if up < 1 {
		up = 1
	}
	down := page + 1
	if down > sum {
		down = sum
	}
	var goodsrooms []*models.Goodsroom
	var goodsroom models.Goodsroom
	goodsrooms, err = goodsroom.List(room, page, pageSize)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
		}
		c.ServeJSON()
		return
	}

	pageData := map[string]interface{}{
		"sum":  sum,
		"up":   up,
		"down": down,
		"data": goodsrooms,
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "查询成功",
		"data": pageData,
	}
	c.ServeJSON()

}
